class Admin::UsersController < ApplicationController
  def new
  end
  def create
    @user = Users.new user_param
    if @user.save
      render json: {msg:'Create user successfully!',status:true}
    else
      render json: {msg:'Create user failed',status:false}
    end
  end

  def show
    user = Users.find(params[:id])
    render json: {user:user}
  end

  def update
    user = Users.find(params[:id])
    if user.update user_param
      render json: {msg:'Save user successfully!',status:true}
    else
      render json: {msg:'Save user failed',status:false}
    end
  end

  def destroy
    user = Users.find(params[:id])
    user.destroy
    render json: {}
  end

  def search
    size = 0
    page = params[:page].to_i
    pageSize = params[:pageSize].to_i
    #binding.pry
    if page>0 and pageSize>0
      id = params[:key].to_i
      begin
        if id == 0
            user = Users.where('email like ?', "%#{params[:key]}%")
            size = user.count
            user = user.limit(pageSize).offset((page-1)*pageSize)
        else
          user = [Users.find(id)]
        end
      rescue Exception
        user = []
      end
    else
      user = []
    end
    render json: {user:user,size:size}
  end

  private
  def user_param
    {email:params[:email],password:params[:password],isAdmin:params[:isAdmin],remark:params[:remark]}
  end
end
